#!/usr/bin/expect -f
log_user 0
set echo  off
set mailserver [lrange $argv 0 0]
set from [lrange $argv 1 1]
set to [lrange $argv 2 2]
set head [lindex $argv 3]
set textfile [lrange $argv 4 4]
set textfd [open $textfile r]
set textcontent [read $textfd ]
set timeout 5
set err 1
set text $head$textcontent
close $textfd
send_user "$to:$mailserver:enter\n"
spawn telnet $mailserver 25
expect "2?? *" {
		send "HELO localhost.com\r"
		expect "2?? *" {
			send "MAIL FROM: <$from>\r"
			expect "2?? *"  {
				send "RCPT TO: <$to>\r"
				expect "2?? *" {
					send "DATA\r"
					expect "3?? *" {
						send "$text\r"
						send ".\r"
						expect "2?? *" {
							set err 0
						} "5?? *" {
							send_user "$to:$mailserver:content return 5xx error\n"
						} "4?? *" {
							send_user "$to:$mailserver:content return 4xx error\n"
						} timeout {
							send_user "$to:$mailserver:content timeout\n"
						}
					} "5?? *" {
						send_user "$to:$mailserver:data return 5xx error\n"
					} "4?? *" {
						send_user "$to:$mailserver:data return 4xx error\n"
					} timeout {
						send_user "$to:$mailserver:data timeout\n"
					}
				} "5?? *" {
					send_user "$to:$mailserver:rcpt return 5xx error\n"
				} "4?? *" {
					send_user "$to:$mailserver:rcpt return 4xx error\n"
				} timeout {
					send_user "$to:$mailserver:rcpt timeout\n"
				}
			} "5?? *" {
				send_user "$to:$mailserver:mail return 5xx error\n"
			} "4?? *" {
				send_user "$to:$mailserver:mail return 4xx error\n"
			} timeout {
				send_user "$to:$mailserver:mail timeout\n"
			}
		} "5?? *" {
			send_user "$to:$mailserver:helo return 5xx error\n"
		} "4?? *" {
			send_user "$to:$mailserver:helo return 4xx error\n"
		} timeout {
			send_user "$to:$mailserver:helo timeout\n"
		}
	} "failed" {
                send_user "$to:$mailserver:connect failed\n"
        } "4?? *" {
		send_user "$to:$mailserver:connect return 4xx error\n"
        } "5?? *" {
		send_user "$to:$mailserver:connect return 5xx error\n"
        } "refused" {
                send_user "$to:$mailserver: connect refused\n"
        } "closed" {
                send_user "$to:$mailserver: connect closed\n"
        } timeout {
                send_user "$to:$mailserver: connect to port 25 timeout\n"
        }
send "QUIT\r"
send \035
expect "telnet>" { 
		send "quit\r"
		close -onexec 1
		wait
		send_user "$to:$mailserver exit\n"
	}
exit $err
